<template>
    <div class="h-full w-full" style="height:100%;overflow: auto;">
      <SplitPanel :style="{ 'flex-direction': 'row !important' }" class="user-page-box">
        <template #left-content>
          <div class="flex justify-between flex-col h-full">
            <a-input-search
              v-model:value="searchValue"
              style="margin-bottom: 8px"
              placeholder="查找机构或部门"
            />
  
            <Tree
              v-model:expandedKeys="state.expandedKeys"
              auto-expand-parent
              :treeData="state.deptTree"
              @select="onTreeSelect"
            >
            </Tree>
          </div>
        </template>
        <template #right-content>
              <a-checkbox-group v-model:value="state.selectData">  
                <a-checkbox v-for="item in plainOptions" :key="item.code" :value="item.code">  
                    <span class="custom-checkbox-content">  
                        <svg-icon name="touxiang" size="18" /> 
                        {{ item.name }}  
                    </span>  
                </a-checkbox>  
            </a-checkbox-group>
        </template>
      </SplitPanel>
    </div>
  </template>
  
  <script setup lang="tsx">
    import { ref, reactive, onMounted, watch } from 'vue';
    import { Tree } from 'ant-design-vue';
    import { baseColumns,  type TableColumnItem } from '@/components/setting/columns';
    import type { TreeDataItem } from '@/core/permission/utils';
    import { SplitPanel } from '@/components/basic/split-panel';
    
    import {
      gePostList
    } from '@/api/organization/station/station';
    import { formatDept2Tree, flatTree } from '@/core/permission/utils';
    import { getDepartmentEntityList } from '@/api/organization/depts/depts';

    interface Props {
      defaultData?: any;
    }
    const props = withDefaults(defineProps<Props>(), {
      defaultData: [{
        defaultSelectData: [],
      }]
    });
    defineOptions({
      name: 'settingStation',
    });
  
    interface State {
      expandedKeys: number[];
      departmentIds: number[];
      originData: any;
      deptTree: TreeDataItem[];
    }
  
  const emit = defineEmits(['updateValue']);  
  
    const updateParentValue = (newVal) => {  
      const parentValue=newVal.map((item) => {
        const index = plainOptions.value.findIndex(option => option.code ===item);
        if(index>=0){
          const selectOption=plainOptions.value[index];
          return {
                NO:selectOption.code,
                NAME:selectOption.name,
                ORG_TYPE:'station'
            }; 
        }
      }); 
      if(parentValue.length<=0){
        const blankData={
                NO:"none",
                NAME:"",
                ORG_TYPE:'station'
            }; 
            parentValue.push(blankData);
      }
      emit('updateValue', parentValue);  
    };  
  
    const searchValue = ref('');
  
    const searchTree = (tree, keyword, includeChildren = false) => {
      const newTree: any = [];
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.title.includes(keyword)) {
          if (!state.expandedKeys.includes(node.key) && node.children && node.children.length) {
            state.expandedKeys.push(node.key);
          }
          newTree.push({
            ...node,
            children: includeChildren ? searchTree(node.children || [], '', true) : [],
          });
        } else if (node.children) {
          const result = searchTree(node.children, keyword, true);
          if (result.length > 0) {
            state.expandedKeys.push(node.key);
            newTree.push({ ...node, children: result });
          }
        }
      }
      return newTree;
    };
  
    
  
    const deptListLoading = ref(false);
  
    const state = reactive<State>({
      parentId: [],
      selectData: [{}],
      departmentIds: [],
      deptTree: [],
      originData: [],
    });
    const plainOptions=ref<any>([]);
  
    /**
     * 获取部门列表
     */
    const fetchDeptList = async () => {
      deptListLoading.value = true;
      const res = await getDepartmentEntityList().finally(() => (deptListLoading.value = false));
      if (res && res.result) {
        const dept = flatTree(res.result);
        state.deptTree = formatDept2Tree(dept, '0');
        state.originData = state.deptTree.map((item) => item);
        state.parentId = [...state.parentId, ...state.deptTree.map((n: any) => Number(n.id))];
      }
    };
  
    /**
     * 点击部门
     */
     const onTreeSelect = (selectedKeys: number[]) => {
      state.departmentIds = selectedKeys;
      loadTableData();
    };
  
    const loadTableData = async () => {
      const data = await gePostList({
        orgId: state.departmentIds.length ? state.departmentIds[0] : '',
      });
      if(props.defaultData.defaultSelectData.length>0){
        props.defaultData.defaultSelectData.map((item)=>{
            state.selectData.push(item.NO);
        })
      }
      plainOptions.value=data?.rows || [];
    };
  
    const columns: TableColumnItem[] = [
      ...baseColumns
    ];
    const onSubMit = async () => {
      return state.selectData;
    };
    const updateSelectData=async(newData)=>{
      state.selectData=newData;
    }
    defineExpose({
      handleSubmit: onSubMit,
      handlerUpdate: updateSelectData,
    });
    onMounted(() => {
      fetchDeptList();
    });
    watch(
        () => state.selectData,
        (newVal) => {
            updateParentValue(newVal);
        },
  );
  </script>
  
  <style lang="less" scoped>
  @import '@/styles/navTheme.less';
  @classBacks: user-page-box;
  .customSetStyle(@classBacks, background-color, 'content-back-user');
  
  :deep(.ant-tree) {
    flex: 1;
  }
  
  .testtitle {
    width: 100%;
    overflow: hidden;
    line-height: 30px;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .testitem {
    position: relative;
    display: flex;
    justify-content: space-between;
    width: 150px;
    align-items: center;
  }
  </style>
  